package com.financial.service.yspay.service.pay.impl;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.financial.service.yspay.connector.SysconfigFeign;
import com.financial.service.yspay.constants.YsServiceEnumConstants;
import com.financial.service.yspay.dto.FinancialYsPayDTO;
import com.financial.service.yspay.service.FinancialYsPayBuildRequestParaService;
import com.financial.service.yspay.service.FinancialYsPayVerifyJsonSignService;
import com.financial.service.yspay.service.pay.FinancialYsWeChatPayService;
import com.financial.service.yspay.utils.DateUtils;
import com.financial.service.yspay.utils.HttpUtils;
import com.financial.service.yspay.utils.JsonUtils;
import com.financial.service.yspay.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author WANGNING
 * @Email wyn20140226@aliyun.com
 * @Description //银盛微信支付服务处理
 * @Date 2019/11/13 9:17
 */
@Service
public class FinancialYsWeChatPayServiceImpl implements FinancialYsWeChatPayService {
    public static final Logger logger = LoggerFactory.getLogger(FinancialYsWeChatPayServiceImpl.class);

    @Value("${ysWechatNotifyUrl}")
    private String ysWechatNotifyUrl;

    @Value("${ysWeChatPayMethod}")
    private String ysWeChatPayMethod;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private FinancialYsPayBuildRequestParaService financialYsPayBuildRequestParaService;

    @Autowired
    private FinancialYsPayVerifyJsonSignService financialYsPayVerifyJsonSignService;

    @Override
    public ApiResult ysWeChatPay(String requestParam) {
        logger.info("FinancialYsWeChatPayServiceImpl.ysWeChatPay()----->获取到的银盛微信请求参数json为:" + requestParam);
        String ysPayWechatJson = sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsPayDTO = JsonUtils.parseObject(ysPayWechatJson);
        /*返回内容初始化*/
        String content = null;
        if (financialYsPayDTO != null) {
            /*组装银盛微信支付参数信息*/
            Map<String, String> param = new HashMap<>();
            param.put("method", ysWeChatPayMethod);
            param.put("partner_id", financialYsPayDTO.getPARTNER_ID());
            param.put("timestamp", DateUtils.getNowTimeStr());
            param.put("charset", financialYsPayDTO.getDEFAULT_CHARSET());
            param.put("sign_type", financialYsPayDTO.getSIGN_ALGORITHM());
            param.put("notify_url", ysWechatNotifyUrl);
            param.put("version", financialYsPayDTO.getVERSION());
            /*获取biz_content业务参数信息*/
            Map<String, Object> bizContent = JsonUtils.jsonToMap(requestParam);
            param.put("biz_content", (String) bizContent.get("biz_content"));
            logger.info("FinancialYsWeChatPayServiceImpl.ysWeChatPay()----->请求银盛微信支付参数为:" + param.toString());
            try {
                Map<String, Object> realResponse = new HashMap<>();
                /*签名*/
                Map<String, String> sPara = financialYsPayBuildRequestParaService.buildRequestPara(param, financialYsPayDTO);
                /*发起请求*/
                logger.info("签名完成的参数：{}", sPara);
                String returnString = HttpUtils.httpsSend(financialYsPayDTO.getYSEPAY_GATEWAY_URL(), sPara);
                //回执参数JSON转map
                Map<String, Object> resultMap = (Map<String, Object>) JSON.parse(returnString);
                Map<String, String> obj = (Map<String, String>) resultMap.get("ysepay_online_weixin_pay_response");
                if (obj == null) {
                    return ApiResult.failure(JsonUtils.objectToJson("银盛返回结果为空"));
                }
                String sign = resultMap.get("sign").toString();
                realResponse.putAll(obj);
                realResponse.put("sign", sign);
                int begin = returnString.indexOf("ysepay_online_weixin_pay_response");
                content = returnString.substring(begin);
                content = content.replace("ysepay_online_weixin_pay_response", "");
                content = content.substring(2, content.length() - 1);
                logger.info("wechat--------------调用银盛微信支付同步回执response" + content);
                /*TODO 验证签名总是出错，需要确认一下验证签名的responseBody到底是哪些参数*/
                boolean verifyResult = financialYsPayVerifyJsonSignService.verifyJsonSign(sign, content, "utf-8", financialYsPayDTO);
                logger.info("FinancialYsWeChatPayServiceImpl.ysWeChatPay()----->微信支付请求回执信息,验签是否成功content:" + content + "验签结果verifyResult--" + verifyResult);
                if (null == content || content.equals("")) {
                    logger.info("FinancialYsSplitServiceImpl.ysSplit()----->验签没有成功:银盛返回结果为空");
                    return ApiResult.failure(JsonUtils.objectToJson("银盛返回结果为空"));
                }
                realResponse.put("verifyResult", verifyResult);
                /*解析contrent*/
                Map<String, Object> contentMap = JsonUtils.jsonToMap(content);
                boolean returnCodeState = contentMap.containsKey("code");
                if (returnCodeState) {
                    Object tempParams = contentMap.get("code");
                    String returnCode = tempParams == null ? null : tempParams.toString();
                    if (returnCode.equalsIgnoreCase(YsServiceEnumConstants.ENUM_BALANCESTATUS_SUC)) {
                        /*10000是支付成功标识*/
                        return ApiResult.success(realResponse);
                    } else {
                        /*失败返回*/
                        return ApiResult.failure(realResponse);
                    }
                } else {
                    /*失败返回*/
                    return ApiResult.failure(realResponse);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ApiResult.failure(requestParam);
    }

}
